from  flask import  Blueprint,jsonify
from flask_restful import  Api,Resource,reqparse
from models.users import db
from  captcha.image import ImageCaptcha
import redis,re,jwt,random,string
from  seest import send_message
from  flask import  current_app,send_file
from  qiniu import Auth
from  werkzeug.security import generate_password_hash,check_password_hash
from  models.users import Usermodel,BookCateModel,BookModel,Collection



#创建蓝图
view=Blueprint('views',__name__)
api=Api(view)




#获取验证码
class  Yan(Resource):
    def get(self):
        parser=reqparse.RequestParser()
        parser.add_argument('mobile')
        args=parser.parse_args()
        mobile=args['mobile']
        print('>>>>>>>>>>,',mobile)
        if not re.findall('^1[3-9]\d{9}$',mobile):
            return jsonify({'code':400,'msg':'手机号格式不正确'})
        resp=send_message.delay(mobile)
        print(resp)
        return jsonify({'code':200,'msg':'获取验证码成功'})


def gent_token(user):
    payload={
        'id':user.id,
        'mobile':user.mobile,
    }
    key = current_app.config.get('SECRET_KEY')
    token = jwt.encode(payload=payload, key=key, algorithm='HS256')
    return token


#注册
class Zhu(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('mobile')
        parser.add_argument('password')
        parser.add_argument('cs')
        args = parser.parse_args()
        mobile = args['mobile']
        password=args['password']
        cs=args['cs']
        if not all([mobile,password,cs]):
            return jsonify({'code':402,'msg':'参数不完整'})
        if not re.findall('^1[3-9]\d{9}$', mobile):
            return jsonify({'code': 400, 'msg': '手机号格式不正确'})
        r=redis.Redis(host='127.0.0.1',password='123',db=5,port=6379)
        c1=r.get(mobile)
        if not c1:
            return jsonify({'code': 400, 'msg': '验证码过期'})
        if c1.decode() != cs:
            return jsonify({'code': 401, 'msg': '验证码错误'})
        names=mobile[7:]+''.join(random.sample(string.ascii_lowercase,6))
        id=''.join(random.sample(string.digits,6))
        password=generate_password_hash(password)
        user=Usermodel(id=id,name=names,mobile=mobile,password=password)
        token=gent_token(user)
        db.session.add(user)
        db.session.commit()
        return jsonify({"msg": '注册成功', "code": 201, 'token': token,'uid':user.id})




#登录
class Deng(Resource):
    def post(self,uuid):
        parser = reqparse.RequestParser()
        parser.add_argument('mobile')
        parser.add_argument('password')
        parser.add_argument('cs')
        args = parser.parse_args()
        mobile= args['mobile']
        password = args['password']
        cs = args['cs']
        if not all([mobile, password,cs]):
            return jsonify({'code': 402, 'msg': '参数不完整'})
        r = redis.Redis(host='127.0.0.1', password='123', db=6, port=6379)
        c1 = r.get(uuid)
        if not c1:
            return jsonify({'code': 400, 'msg': '图片验证码过期'})
        if c1.decode().lower() != cs.lower():
            return jsonify({'code': 401, 'msg': '图片验证码错误'})
        user = Usermodel.query.filter_by(mobile=mobile).first()
        token = gent_token(user)
        if not check_password_hash(user.password,password):
            return jsonify({'code': 203, 'msg': '密码错误'})
        return jsonify({'code': 200, 'msg': '登录成功',token:'token', 'uid':user.id})









#图片验证码
class Tu(Resource):
    def get(self,uuid):
        cs=''.join(random.sample(string.digits+string.ascii_letters,4))
        cap=ImageCaptcha()
        img=cap.generate(cs)
        r = redis.Redis(host='127.0.0.1', password='123', db=6, port=6379)
        r.set(uuid,cs,ex=5*60)
        r.close()
        return send_file(img,mimetype='png')














#七牛云
class Qi(Resource):
    def get(self):
        access_key = 'qo0n1dt7IzUdMBmh0Wh7mbBhoEAmRYYpxjCBNTpB'
        secret_key = 'CshMtuCYvP_Ul4LFj78iDvve0QPzZ_c0g1oDUtJ4'
        q = Auth(access_key, secret_key)
        bucket_name = 'admin1222'
        token = q.upload_token(bucket_name)
        return jsonify({'code': 200, 'token': token})




#修改图片
class Xou(Resource):
    def get(self,id):
       try:
           user=Usermodel.query.filter_by(id=id).first()
           user_data={
               'id': user.id,
               'name':user.name,
               'mobile':user.mobile,
               'xing':user.xing,
               'img':user.img,
               'shi': str(user.shi),
               'xuan':user.xuan
           }
           return jsonify({'code':200,'msg': '用户信息获取成功','data':user_data})
       except Exception as e:
           print('>>>>>>>',e)
           return jsonify({'msg':'用户信息获取失败','code':500})
    def put(self,id):
        parser = reqparse.RequestParser()
        parser.add_argument('img')
        args = parser.parse_args()
        img= args['img']
        Usermodel.query.filter_by(id=id).update({'img':img})
        db.session.commit()
        return jsonify({'code':200,'msg':'修改成功'})





#分类
class Lei(Resource):
    def get(self):
        ser=BookCateModel.query.all()
        list=[]
        for i in ser:
            list.append({
                'id':i.id,
                'name':i.name,
            })
        return  jsonify(list)



#书籍
class Ji(Resource):
    def get(self,id):
        se = BookModel.query.filter_by(set_id=id)
        list = []
        for i in se:
            list.append({
                'id':i.id,
                'name':i.name,
                'names':i.names,
                'img':i.img,
                'set_id':i.set_id
            })
        return jsonify(list)


#收藏表
class Chang(Resource):
    def get(self,id):
        se=Collection.query.filter_by(ses_id=id)
        list = []
        for i in se:
            list.append({
                'id': i.id,
                'name': i.name,
                'names': i.names,
                'img': i.img,
                'xiang':i.xiang,
                'shou':i.shou,
                'ses_id': i.ses_id
            })
        return jsonify(list)


#收藏
class Sou(Resource):
    def put(self,id):
        user=Collection.query.filter_by(id=id).first()
        if user.shou=='已收藏':
            return jsonify({'code': 400, 'msg': '已收藏，不能再点'})
        user.shou='已收藏'
        db.session.commit()
        return jsonify({'code': 200, 'msg': '收藏小说成功'})


#收藏了
class Ja(Resource):
    def get(self):
        use = Collection.query.filter_by(shou='已收藏')
        list = []
        for i in use:
            list.append({
                'id': i.id,
                'name': i.name,
                'names': i.names,
                'img': i.img,
                'xiang': i.xiang,
                'shou':i.shou,
            })

        return jsonify(list)


# 获取验证码
api.add_resource(Yan,'/yan/')


#注册
api.add_resource(Zhu,'/zhu/')

#登录
api.add_resource(Deng,'/deng/<uuid>/')


#图片验证码
api.add_resource(Tu,'/tu/<uuid>/')


#七牛云
api.add_resource(Qi,'/qi/')


#修改图片
api.add_resource(Xou,'/xou/<int:id>/')



#分类
api.add_resource(Lei,'/lei/')

#书籍
api.add_resource(Ji,'/ji/<int:id>/')

#收藏表
api.add_resource(Chang,'/chang/<int:id>/')

#收藏
api.add_resource(Sou,'/sou/<int:id>/')


#收藏了
api.add_resource(Ja,'/ja/')













